package models

import (
	"cubeAdmin/dto"
	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
)

type SysRoleMenu struct {
	Id     int64
	MenuId *SysMenu `orm:"column(menu_id);rel(fk)"`
	RoleId *SysRole `orm:"column(role_id);rel(fk)"`
}

func init() {
	orm.RegisterModel(new(SysRoleMenu))
}

func BatchRoleMenuAdd(menu dto.RoleMenu) {
	o := orm.NewOrm()
	o.Raw("delete from sys_role_menu WHERE role_id = ?", menu.Id).Exec()

	var roleMenus []SysRoleMenu
	for _, val := range menu.Menus {
		var menus = SysMenu{Id: val.Id}
		var roles = SysRole{Id: menu.Id}
		roleMenus = append(roleMenus, SysRoleMenu{MenuId: &menus, RoleId: &roles})
	}
	if _, err := o.InsertMulti(100, roleMenus); err != nil {
		logs.Error(err)
	}
}

// GetRoleMenuId 通过roleId获取角色对应的菜单ids
func (e *SysRoleMenu) GetRoleMenuId(roleId int) ([]int64, error) {
	var menus []SysRoleMenu
	o := orm.NewOrm()
	qs := o.QueryTable("sys_role_menu").Filter("role_id", roleId)

	if _, err := qs.All(&menus); err != nil {
		return nil, err
	}
	menuIds := make([]int64, 0)

	for i := 0; i < len(menus); i++ {
		menuIds = append(menuIds, menus[i].MenuId.Id)
	}
	return menuIds, nil
}
